package com.haohan.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haohan.controller.utils.R;
import com.haohan.domain.ServerInfo;
import com.haohan.service.ServerInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/servers")
public class ServerController {

    @Autowired
    private ServerInfoService serverInfoService;


    @GetMapping
    public R getAll(){
        return new R(true, serverInfoService.list());
    }


    @PostMapping
    public R save(@RequestBody ServerInfo server) throws IOException {
        boolean flag = serverInfoService.save(server);
        return new R(flag, flag ? "添加成功^_^" : "添加失败-_-!");
    }

    @PutMapping
    public R update(@RequestBody ServerInfo server) throws IOException {
        boolean flag = serverInfoService.updateById(server);
        return new R(flag, flag ? "修改成功^_^" : "修改失败-_-!");
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true, serverInfoService.getById(id));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(serverInfoService.removeById(id));
    }


//    @GetMapping("{currentPage}/{pageSize}")
//    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
//        IPage<ServerInfo> page = serverInfoService.getPage(currentPage, pageSize);
//        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
//        if (currentPage > page.getPages()) {
//            page = serverInfoService.getPage((int) page.getPages(), pageSize);
//        }
//        return new R(true, page);
//    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, ServerInfo server) {
        IPage<ServerInfo> page = serverInfoService.getPage(currentPage,pageSize, server);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()) {
            page = serverInfoService.getPage((int) page.getPages(), pageSize, server);
        }
        return new R(true, page);
    }
    

}

















